package com.platform.utils;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.util.JdbcConstants;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangfei23 on 2018/11/23.
 */
public class MyBatisSqlUtils {

    /**
     * 构建SQL
     *
     * @param sql
     * @return
     */
    public static String rebuildSql(String sql) {
        String tenantId = ThreadLocalUtil.get(ThreadLocalUtil.TENANT_ID_KEY);

        if (StringUtils.isEmpty(tenantId)) {
            tenantId = ThreadLocalUtil.DEFAULT_TENANT_ID;
        }

        // 新建 MySQL Parser
        SQLStatementParser parser = new MySqlStatementParser(sql);

        // 使用Parser解析生成AST，这里SQLStatement就是AST
        SQLStatement statement = parser.parseStatement();

        // 使用visitor来访问AST
        MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
        statement.accept(visitor);

        // Map  Key :tableName  V:操作类型 select  insert update delete
        Map<TableStat.Name, TableStat> tables = visitor.getTables();
        Map<String, String> mappings = new HashMap<>(tables.size());
        for (Map.Entry<TableStat.Name, TableStat> entry : tables.entrySet()) {
            String tableName = entry.getKey().getName();
            StringBuilder tableNameBuilder = new StringBuilder();
            tableNameBuilder.append("`")
                    .append(tenantId)
                    .append("`")
                    .append(".")
                    .append("`")
                    .append(tableName)
                    .append("`");
            mappings.put(tableName, tableNameBuilder.toString());
        }

        return SQLUtils.refactor(sql, JdbcConstants.MYSQL, mappings);
    }
}
